package org.an.proj.contacts.ui.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.ArrayList;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
import link.api.LinkApi;
import link.config.AgentConfig;
import link.model.AgentInfoVo;
import link.service.LogoutUtil;
import org.an.ku.base.BaseFragment;
import org.an.ku.util.ToastUtil;
import org.an.ku.view.MyHorizontalProgressBar;
import org.an.ku.view.MyTextView;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.R;
import org.an.proj.contacts.config.LogUtil;
import org.an.proj.contacts.model.response.Result;
import org.an.proj.contacts.net.service.retrofit.call.SimpleCallback;
import org.an.proj.contacts.net.service.retrofit.upload.ProgressListener;
import org.an.proj.contacts.net.service.retrofit.upload.UploadHelper;
import org.an.proj.contacts.net.service.retrofit.util.ServiceGenerator;
import retrofit2.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 创建时间：2016年10月13日15:09 <br>
 * 作者：fuchaoyang <br>
 * 描述：我的Fragment
 * /storage/emulated/0/DCIM/Camera/IMG_20170403_152711.jpg
 */
public class MineFragment extends BaseFragment {
  @Bind(R.id.iv_avatar) ImageView mIvAvatar;
  @Bind(R.id.tv_name) MyTextView mTvName;
  @Bind(R.id.tv_user_code) MyTextView mTvUserCode;
  @Bind(R.id.pg_upload) MyHorizontalProgressBar mPgUpload;

  private Call<Result> mCall;
  private Call<Result> mUploadImageCall;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_mine, container, false);
    ButterKnife.bind(this, view);
    init();
    return view;
  }

  private void init() {
    AgentInfoVo agentInfo = AgentConfig.getInstance().getAgentInfo();
    if (agentInfo == null) {
      LogoutUtil.logout("请重新登录");
      return;
    }
    mTvName.setText(agentInfo.name);
    mTvUserCode.setText(agentInfo.usercode);

    if (!TextUtils.isEmpty(agentInfo.avatar)) {
      Picasso.with(MyApplication.getInstance())
          .load(agentInfo.avatar)
          .error(R.drawable.ic_launcher)
          .placeholder(R.drawable.ic_launcher)
          .transform(new CropCircleTransformation())
          .fit()
          .centerCrop()
          .into(mIvAvatar);
    } else {
      // 如果没有url，必须要单独.transform(new CropCircleTransformation())，走error和placeholder不会处理圆形
      // 或者这里不处理，而用CircleImageView
      // transform为圆形的时候，缓存的图片到底是方形的还是圆形的，如果是方形的就最好用 cirView
      Picasso.with(MyApplication.getInstance())
          .load(R.drawable.ic_launcher)
          .fit()
          .centerCrop()
          .transform(new CropCircleTransformation())
          .into(mIvAvatar);
    }
  }

  // ============ 如果需要切换到该Tab以及在该Tab跳转页面回来时执行某操作 =======================

  /**
   * 该Tab跳转页面返回到该页面时回调
   */
  @Override public void onResume() {
    super.onResume();
    if (!isHidden()) doAction();
  }

  /**
   * 该Fragment hide,show状态发生变化时回调（由于重写了FragmentTabHost,切换tab时调用hide,show而不是detach和attach,所以会回调该方法）
   */
  @Override public void onHiddenChanged(boolean hidden) {
    if (!hidden) doAction();
  }
  // ===================================

  private void doAction() {
    ToastUtil.toast(getContext(), "do something");
    if (mCall != null) {
      mCall.cancel();
    }
    mCall = ServiceGenerator.createService(LinkApi.class).getHomePageData();
    mCall.enqueue(new SimpleCallback<Result>() {
      @Override public void onResponse(Call<Result> call, Result entity, boolean isSuccess) {
        if (entity != null && entity.errno != 0) {
          ToastUtil.toast(MyApplication.getInstance(), "load homepage data: " + entity.error);
        }
      }
    });
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    ButterKnife.unbind(this);
  }

  /**
   * 编辑头像
   */
  @OnClick(R.id.iv_avatar) public void onClick() {
    ImagePicker.getInstance().setMultiMode(false).setCrop(false);
    ImagePicker.getInstance().start(this, 303);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    ArrayList<ImageItem> images = null;
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      if (data != null) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
      }
    } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
      if (data != null) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
      }
    }

    if (images != null && images.size() > 0) {
      //compress(new File(images.get(0).path));
      uploadImage(new File(images.get(0).path));
      /*Picasso.with(MyApplication.getInstance())
          .load(new File(images.get(0).path))
          .error(R.drawable.ic_launcher)
          .transform(new CropCircleTransformation())
          .fit()
          .centerCrop()
          .into(mIvAvatar);*/
    }
  }

  private void compress(File file) {
    LogUtil.e("compress", "原图片大小:" + file.length());
    Luban.get(MyApplication.getInstance()).load(file)                     //传人要压缩的图片
        .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
        .setCompressListener(new OnCompressListener() { //设置回调

          @Override public void onStart() {
            //  压缩开始前调用，可以在方法内启动 loading UI
          }

          @Override public void onSuccess(File file) {
            //  压缩成功后调用，返回压缩后的图片文件 可以修改luban代码，添加支持设置压缩后的文件目录
            // 文件地址：/data/user/0/包名/cache/luban_disk_cache/时间戳.jpg
            uploadImage(file);
          }

          @Override public void onError(Throwable e) {
            //  当压缩过去出现问题时调用
          }
        }).launch();    //启动压缩
  }

  private void uploadImage(File file) {
    mUploadImageCall = ServiceGenerator.createService(LinkApi.class, new ProgressListener() {
      @Override public void onProgress(final long progress, final long total, boolean done) {
        mPgUpload.post(new Runnable() {
          @Override public void run() {
            mPgUpload.setProgress(progress * 100.f / total);
          }
        });
      }
      //}).uploadImage(PartGenerator.createPartFromFile(MediaType.parse("image/jpeg"), "file", file));
    }).uploadImage(UploadHelper.createRequestBodyParams("file", file.getAbsolutePath()));

    mUploadImageCall.enqueue(new SimpleCallback<Result>() {
      @Override public void onResponse(Call<Result> call, Result entity, boolean isSuccess) {
        if (isSuccess) {
          mPgUpload.setProgress(100);
          init();
        } else {
          mPgUpload.setProgress(-1);
        }
      }
    });
  }
}
